import express from 'express';
import fs, { readFileSync } from 'fs';
import path, { dirname } from 'path';
import url from 'url';
import multer from 'multer'
import {videoTools} from '../../utils/index.js'
const __dirname = dirname(url.fileURLToPath(import.meta.url));
const app = express();
app.use(express.json())
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname,'/uploads'))
    },
    filename: function (req, file, cb) {
        cb(null, `${req.body.index}-${req.body.name}`)
    }
})

const uploadConfig = multer({ storage})

const upload = app.post('/tools/upload',uploadConfig.single('file'), (req, res) => {
    res.send({
        code: 200,
        data: req.file
    })
})
// 合并文件
const merge = app.post('/tools/merge', (req, res) => {
    console.log('cwd:',process.cwd())
    // 读取uploads下的所有文件
    const originFileName = req.body.name
    const dirPath = path.join(__dirname, 'uploads/')
    const files = fs.readdirSync(dirPath);

    const sortedFiles = files.sort((a, b) => {
        const aIndex = parseInt(a.split('-')[0]);
        const bIndex = parseInt(b.split('-')[0]);
        return aIndex - bIndex;
    });
    // 合并文件
    const filepath = path.join(__dirname, '/files', originFileName);
    sortedFiles.forEach(item => {
        const inputPath = path.join(dirPath, item);
        const file = readFileSync(inputPath)
        fs.appendFileSync(filepath, file)
        fs.unlinkSync(inputPath)
    })

    res.json({
        code: 200,
        msg: '合并成功',
        data: {
            url: '123456'
        }
    })
})

const editVideo = app.post('/tools/editVideo', async(req, res) => {
    const result = await videoTools(req.body)
    console.log('finish')
    res.json({
        msg: '编辑成功',
        code: 200,
        data: {
            name: result
        }
    })
})

const downloadFile = app.post('/tools/download', (req, res) => {
    const filePath = path.join(process.cwd(),'/router/tools/files/',req.body.name)
    console.log('下载文件：',filePath)
    const fileStream = fs.readFileSync(filePath);
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent(req.body.name)}`);
    res.send(fileStream)
    fs.unlinkSync(filePath)
})

export { upload, merge ,editVideo,downloadFile}